package com.example.administrator.testc.RXDemo;/**
 * Created by Administrator on 2016/6/27.
 */

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.administrator.testc.R;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>类描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>属性描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>方法描述
 */
public class TestMain extends Activity {

    private Button button;
    private Subscriber<String> observer;
    private Observable observable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_button_layout);
        button = (Button) findViewById(R.id.button);
        observer = new Subscriber<String>() {
            @Override
            public void onNext(String str) {
                Log.i("TAGSS", "Item: " + str);
                Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
                throw new NullPointerException();
            }

            @Override
            public void onCompleted() {
                Log.i("TAGSS", "Completed!");
                this.unsubscribe();
                Log.i("TAGSS", "unsunbscribe : " + this.isUnsubscribed());
            }

            @Override
            public void onError(Throwable e) {
                Log.i("TAGSS", "Error!");
                this.unsubscribe();
                Log.i("TAGSS", "unsunbscribe : " + this.isUnsubscribed());
            }
        };
        String[] words = {"Hello", "Hi", "Aloha"};
        observable = Observable.from(words);
        observable
                .flatMap(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        return s;
                    }
                })
                .filter(new Func1<String, Boolean>() {

                    @Override
                    public Boolean call(String s) {
                        if (s.contains("A"))
                            return true;
                        return false;
                    }
                })
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        return s;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                observable.subscribe(observer);
            }
        });
    }
}
